package com.yeskery.nut.bind.validator;

import com.yeskery.nut.bind.DataBindException;
import jakarta.validation.*;

import java.util.Set;
import java.util.stream.Collectors;

/**
 * 基于Hibernate的自定义方法参数验证处理器
 * @author sprout
 * @version 1.0
 * 2022-09-01 18:03
 */
public class HibernateMethodParamValidatorHandler extends BaseAnnotationCustomMethodParamValidatorHandler {

    /** 验证器对象 */
    private final Validator validator;

    /**
     * 构建基于Hibernate的自定义方法参数验证处理器
     */
    public HibernateMethodParamValidatorHandler() {
        super(Valid.class);
        try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
            validator = factory.getValidator();
        }
    }

    @Override
    public Set<ErrorValidResult> handle(Object parameter) {
        try {
            Set<ConstraintViolation<Object>> constraintViolationSet = validator.validate(parameter);
            return constraintViolationSet.stream()
                    .map(v -> new ErrorValidResult(v.getPropertyPath().toString(), v.getMessage()))
                    .collect(Collectors.toSet());
        } catch (UnexpectedTypeException e) {
            throw new DataBindException("Parameter Valid Error", e);
        }
    }
}
